import { Component, OnInit, TemplateRef } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { userCouponStatusArr } from '../recyc-market-manage.pipe';
import { LoveMakeupCouponService } from '../services/love-makeup-coupon.service';

@Component({
  selector: 'app-love-user-makeup-coupon',
  templateUrl: './love-user-makeup-coupon.component.html',
  styleUrls: ['./love-user-makeup-coupon.component.scss']
})
export class LoveUserMakeupCouponComponent implements OnInit {

  routeParams: any = {};
  // 加价券类型
  couponTypeOptions = [
    { value: 1, label: '百分比券' },
    { value: 2, label: '满加券' }
  ];
  // 适用用户
  userTypeOptions = [
    { value: 1, label: 'C端' },
    { value: 2, label: 'B端' }
  ];
  // 适用成色
  userConditionOptions = [
    { value: 1, label: '二手机' },
    { value: 2, label: '准新机' }
  ];
  searchOptions = [
    { type: 1, labelText: '用户', valueKey: 'userInfo', value: '', placeholder: '请输入用户ID/昵称/联系方式' },
    { type: 1, labelText: '加价券', valueKey: 'couponNo', value: '', placeholder: '请输入加价券ID/名称' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'statusStr',
      value: [],
      multiple: true,
      notTostr: false,
      selectOptions: [...userCouponStatusArr],
    },
    { type: 3, labelText: '领取时间', valueKey: ['getBeginTime', 'getEndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '过期时间', valueKey: ['endBeginTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '使用时间', valueKey: ['useBeginTime', 'useEndTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // table check
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  // 撤回加价券 Modal
  isVisible = false;
  submitLoading = false;
  validateForm!: FormGroup;
  makeupItem: any = null;

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    private services: LoveMakeupCouponService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      remark: ['', [Validators.required]]
    });
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      type: 3,
      pageNum: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getUserCouponList(params);
    this.tableParams.loading = false;
    
    if (code === 0) {
      const { list, total } = data || {};
      this.tableParams.tableData = list || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    if (this.routeParams.couponNo) {
      let findIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'couponNo');
      this.searchOptions[findIndex].value = this.routeParams.couponNo;
      this.searchParams.couponNo = this.routeParams.couponNo;
    }

    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 查看原因
  viewReason(tplContent: TemplateRef<{}>) {
    this.modal.create({
      nzTitle: '撤回原因',
      nzContent: tplContent,
      nzFooter: null,
      nzClosable: true,
    });
  }

  /**
   * ----------------------------------------------------------------
   * 撤回加价券
   * ----------------------------------------------------------------
   */
  showMakeupModal(type: number, item?: any) {
    if (type === 0 && !this.setOfCheckedId.size) {
      this.message.warning('请先勾选所需操作项');
      return
    }
    if (type === 1) {
      this.makeupItem = item;
    }
    this.validateForm.reset();
    this.validateForm.get('remark')?.setValue('');
    this.isVisible = true;
  }

  async submitForm() {
    if (this.validateForm.value.remark === '') {
      this.message.warning('请先输入撤回原因');
      return
    }
    let params: any = {
      ...this.validateForm.value,
      type: 3,
      ids: []
    }
    params.ids = !this.makeupItem ? [...this.setOfCheckedId] : [this.makeupItem.id];
    console.log('chehui', params);
    // return

    this.submitLoading = true;
    const res: any = await this.services.stopUserCoupon(params);
    this.submitLoading = false;

    if (res.code === 0) {
      this.message.success('操作成功');
      this.isVisible = false;
      this.setOfCheckedId.clear();
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * Table Check
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData
      .filter(({ status }) => status === 1)
      .forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter(({ status }) => status === 1);
    this.checked = listOfEnabledData.every(item => this.setOfCheckedId.has(item.id)) && listOfEnabledData.length > 0;
    this.indeterminate = listOfEnabledData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
}
